package com.pallass;

import java.nio.charset.StandardCharsets;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.pallass.config.JpaConfiguration;
import com.pallass.config.PallassRootConfig;
import com.pallass.config.PallassWebConfig;
import com.pallass.config.SecurityConfiguration;

/**
 * 配置DispatcherServlet
 * 
 * @author Houor
 *
 * @createTime: 2016-12-20 21:21
 */
public class PallassWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	/*
	 * 指定Root配置
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { PallassRootConfig.class, JpaConfiguration.class, SecurityConfiguration.class };
	}

	/*
	 * 指定配置类
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {

		return new Class<?>[] { PallassWebConfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		// 将DispatcherServlet映射到 "/"
		return new String[] { "/" };
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {

		FilterRegistration.Dynamic fr = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter());
		fr.setInitParameter("encoding", String.valueOf(StandardCharsets.UTF_8));
		fr.setInitParameter("forceEncoding", "true");
		fr.addMappingForUrlPatterns(null, true, "/*");

		FilterRegistration.Dynamic stat = servletContext.addFilter("stat", new WebStatFilter());
		stat.setInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		stat.addMappingForUrlPatterns(null, true, "/*");

		ServletRegistration.Dynamic statViewServlet = servletContext.addServlet("statViewServlet", new StatViewServlet());
		statViewServlet.setInitParameter("allow", "*");
		statViewServlet.addMapping("/druid/*");

		super.onStartup(servletContext);

	}

}